package com.example.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.constant.RedisConstant;
import com.example.common.redis.RedisUtils;
import com.example.system.domain.Item;
import com.example.system.domain.Project;
import com.example.system.domain.User;
import com.example.system.mapper.ProjectMapper;
import com.example.system.mapper.UserMapper;
import com.example.system.service.CountService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CountServiceImpl implements CountService {
    final String key = RedisConstant.getList_Item;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Map<String, Object> getProjectLine() {
        List<Project> projects = projectMapper.selectList(new LambdaQueryWrapper<>());
        List<Item> items = (List<Item>) redisUtils.get(key);
        List<Item> list = items.stream().sorted(Comparator.comparing(Item::getCreateTime)).collect(Collectors.toList());
        Item first = list.get(0);//第一个
        Item last = list.get(list.size() - 1);//最后一个
        int end_year = Integer.parseInt(last.getCreateTime().toString().split("-")[0]);
        int end_mouth = Integer.parseInt(last.getCreateTime().toString().split("-")[1]);
        List<String> types = projects.stream().map(Project::getType).distinct().collect(Collectors.toList());
        Map<String, List<Item>> list_groupBy_type = items.stream().collect(Collectors.groupingBy(item -> item.getProject().getType()));
        List<List<Long>> data = new ArrayList<>();
        List<String> x_ = new ArrayList<>();//横坐标
        List<String> finalX_ = x_;
//        list_groupBy_type.values().stream().peek(itemList -> {
//            int start_year = Integer.parseInt(first.getCreateTime().toString().split("-")[0]);
//            int start_mouth = Integer.parseInt(first.getCreateTime().toString().split("-")[1]);
//            List<Long> list1 = new ArrayList<>();
//            while (start_year < end_year || (start_year == end_year && start_mouth <= end_mouth)) {
//                String x = start_year + "-" + start_mouth;
//                finalX_.add(x);
//                long count = itemList.stream().filter(o -> o.getCreateTime().toString().startsWith(x)).count();
//                list1.add(count);
//                start_mouth++;
//                if (start_mouth == 13) {
//                    if (start_year == end_year) break;
//                    start_mouth = 1;
//                    start_year++;
//                }
//            }
//            data.add(list1);
//        }).collect(Collectors.toList());
        list_groupBy_type.forEach((k, v) -> {
            int start_year = Integer.parseInt(first.getCreateTime().toString().split("-")[0]);
            int start_mouth = Integer.parseInt(first.getCreateTime().toString().split("-")[1]);
            List<Long> list1 = new ArrayList<>();
            while (start_year < end_year || (start_year == end_year && start_mouth <= end_mouth)) {
                String x = start_year + "-" + start_mouth;
                finalX_.add(x);
                long count = v.stream().filter(o -> o.getCreateTime().toString().startsWith(x)).count();
                list1.add(count);
                start_mouth++;
                if (start_mouth == 13) {
                    if (start_year == end_year) break;
                    start_mouth = 1;
                    start_year++;
                }
            }
            data.add(list1);
        });//2265
        Map<String, Object> map = new HashMap<>();
        //横坐标
        x_ = finalX_.stream().distinct().collect(Collectors.toList());
        map.put("x", x_);
        //折线数据
        map.put("data", data);
        //项目种类
        map.put("type", types);
        return map;
    }

    @Override
    public List<Map<String, Integer>> getUserInsert() {
        Map<Integer, List<User>> map = userMapper.getUserList().stream().collect(Collectors.groupingBy(user -> Integer.parseInt(user.getCreateTime().toString().split("-")[0])));
        Map<Integer, Integer> map1 = new HashMap<>();
//        map.entrySet().stream().peek(o -> map1.put(o.getKey(), o.getValue().size())).collect(Collectors.toList());
        map.forEach((k, v) -> map1.put(k, v.size()));
        TreeMap<Integer, Integer> treeMap = new TreeMap<>(map1);
        List<Map<String, Integer>> list = new ArrayList<>();
        treeMap.forEach((k, v) -> {
            Map<String, Integer> m = new HashMap<>();
            m.put("year", k);
            m.put("count", v);
            list.add(m);
        });
        return list;
    }

    @Override
    public Map<String, Object> getDynamicSortLineChart() {
        List<Item> items = (List<Item>) redisUtils.get(key);
        List<Item> list = items.stream().sorted(Comparator.comparing(Item::getCreateTime)).collect(Collectors.toList());
        int first = Integer.parseInt(list.get(0).getCreateTime().toString().split("-")[0]);//第一个
        int last = Integer.parseInt(list.get(list.size() - 1).getCreateTime().toString().split("-")[0]);//最后一个
        List<String> types = items.stream().map(Item::getProject).collect(Collectors.toList()).stream().map(Project::getType).distinct().collect(Collectors.toList());
        Map<String, List<Item>> list_groupBy_type = items.stream().collect(Collectors.groupingBy(item -> item.getProject().getType()));
        List<List<Object>> listList = new ArrayList<>();
        List<Object> l = new ArrayList<>();
        l.add("type");
        l.add("year");
        l.add("num");
        listList.add(l);
        list_groupBy_type.forEach((type, item) -> {
            for (int i = first; i < last; i++) {
                List<Object> l1 = new ArrayList<>();
                l1.add(type);
                int y = i;
                l1.add(y);
                long num = item.stream().filter(o -> Integer.parseInt(o.getCreateTime().toString().split("-")[0]) <= y).count();
                l1.add(num);
                listList.add(l1);
            }
        });
        Map<String, Object> map = new HashMap<>();
        //数据
        map.put("data", listList);
        //最小年份
        map.put("year", first);
        //项目种类
        map.put("type", types);
        return map;
    }

    @Override
    @SneakyThrows
    public Map<String, Object> getContribution() {
        String url = "https://gitee.com/cai-bin00_admin";
        Document document = Jsoup.parse(new URL(url), 1000000);
        Elements boxLess = new Elements();
        boxLess.addAll(document.getElementsByClass("box less"));
        boxLess.addAll(document.getElementsByClass("box little"));
        boxLess.addAll(document.getElementsByClass("box some"));
        boxLess.addAll(document.getElementsByClass("box many"));
        boxLess.addAll(document.getElementsByClass("box much"));

        Elements dates = document.getElementsByAttribute("date");
        String start = dates.first().toString().split("个贡献：")[1].split("\" date=\"")[0];
        String end = dates.last().toString().split("个贡献：")[1].split("\" date=\"")[0];

        List<List<Object>> data = new ArrayList<>();
        boxLess.forEach(box -> {
            String s = box.toString();
            String[] split = s.split("data-content=\"")[1].split("\"")[0].split("个贡献：");
            int num = Integer.parseInt(split[0]);
            String day = split[1];
            List<Object> list = new ArrayList<>();
            list.add(day);
            list.add(num);
            data.add(list);
        });
        Map<String, Object> resultMap = new HashMap<>();

        List<String> date = new ArrayList<>();
        date.add(start);
        date.add(end);
        resultMap.put("date", date);
        resultMap.put("data", data);
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> getPieWithScrollableLegend() {
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<>());
        List<Item> items = (List<Item>) redisUtils.get(key);
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        users.stream().peek(o -> {
            Integer userId = o.getUserId();
            long value = items.stream().filter(i -> i.getCreateBy().equals(userId)).count();
            if (value != 0) {
                map.put("value", value);
                map.put("name", o.getName());
                list.add(map);
            }
        }).collect(Collectors.toList());
        return list;
    }
}
